package com.orange.delivery.business.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.dao.OptimisticLockingFailureException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.orm.ObjectRetrievalFailureException;

import com.orange.delivery.business.ManageMarketBusiness;
import com.orange.delivery.business.transform.MarketTransform;
import com.orange.delivery.consumersoap.GererMarche;
import com.orange.delivery.dao.MarketRepository;
import com.orange.delivery.model.MarketBean;
import com.orange.delivery.model.persistent.Market;
import com.orange.delivery.technicalservice.exception.InvalidMarketException;
import com.orange.delivery.technicalservice.exception.InvalidQueryException;
import com.orange.delivery.technicalservice.exception.NotFoundException;
import com.orange.delivery.technicalservice.exception.TechnicalException;
import com.orange.delivery.technicalservice.tool.MultiValuedMap;

/**
 * Business implementation for Market component
 * 
 * @author Clara
 */
public class ManageMarketBusinessImpl implements ManageMarketBusiness {

	private static final Logger LOG = LoggerFactory.getLogger(ManageMarketBusinessImpl.class);

	@Autowired
	private MarketRepository marketRepository;

	public void setMarketRepository(MarketRepository marketRepository) {
		this.marketRepository = marketRepository;
	}

	private GererMarche gererMarche = null;

	/**
	 * GererMarche setter filled by dependency injection
	 * 
	 * @param gererMarche
	 *            the gererMarche to inject
	 */
	public void setGererMarche(GererMarche gererMarche) {
		this.gererMarche = gererMarche;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Map<Integer, MarketBean> findAllMarkets() throws NotFoundException {

		// markets are found into database AND webservice

		Map<Integer, MarketBean> marketBeanMap = null;

		// *************/
		// First : get markets from database
		// *************/
		Collection<Market> marketPersistCollection = null;
		try {
			marketPersistCollection = marketRepository.findAll();

			if (marketPersistCollection == null || marketPersistCollection.isEmpty()) {
				String message = "no market found";
				LOG.warn(message);
				throw new NotFoundException(message);
			}

			marketBeanMap = MarketTransform.persistant2BeanMap(marketPersistCollection);
		} catch (DataAccessException e) {
			String message = "Error getting all markets";
			LOG.error(message, e);
			throw new TechnicalException(message, e);
		}

		// *************/
		// SECOND : get markets from webservice
		// *************/
		marketBeanMap.putAll(gererMarche.findAllMarkets());

		return marketBeanMap;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Integer createMarket(MarketBean marketBean) throws InvalidMarketException {

		// markets are always created into database (because webservices are
		// mocked)

		Market marketPersist = MarketTransform.bean2Persistant(marketBean);

		try {
			// Checking there is no other market with the same name
			if (marketRepository.existsMarketWithName(marketBean.getName())) {
				LOG.warn("A market with the same name (" + marketBean.getName() + ") already exists");
				throw new InvalidMarketException("A market with the same name (" + marketBean.getName() + ") already exists");
			}

			// No problem ... we can persist the new market
			marketPersist = marketRepository.save(marketPersist);

			return marketPersist.getId();
		} catch (DataAccessException e) {
			// Other technical errors
			String message = "Error creating market " + marketBean.getName();
			LOG.error(message, e);
			throw new TechnicalException(message, e);
		}

	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void modifyMarket(MarketBean marketBean) throws InvalidMarketException, NotFoundException {

		// markets are always modified into database (because webservices are
		// mocked)

		Market marketPersist;

		try {
			marketPersist = marketRepository.findOne(marketBean.getId());
			if (marketPersist == null) {
				String message = "Market #" + marketBean.getId() + " not available";
				LOG.error(message);
				throw new NotFoundException(message);
			}
		} catch (ObjectRetrievalFailureException e) {
			String message = "Error modifying market " + marketBean.getName();
			LOG.error(message, e);
			throw new InvalidMarketException(message, e);
		} catch (DataAccessException e) {
			String message = "Data access error " + marketBean.getId();
			LOG.error(message, e);
			throw new TechnicalException(message, e);
		}

		// check the versions
		if (marketPersist.getVersion() != marketBean.getVersion())
			throw new OptimisticLockingFailureException("market version has changed");

		// if market name has changed ...
		if (!marketPersist.getName().equals(marketBean.getName())) {
			// Checking there is no other market with the same new name
			if (marketRepository.existsMarketWithName(marketBean.getName())) {
				LOG.warn("A market with the same name (" + marketBean.getName() + ") already exists");
				throw new InvalidMarketException("A market with the same name (" + marketBean.getName() + ") already exists");
			}
		}
		marketPersist.setName(marketBean.getName());
		marketPersist.setDescription(marketBean.getDescription());

	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void deleteMarket(Integer idMarket) throws InvalidMarketException {

		// markets are always deleted into database (because webservices are
		// mocked)

		try {
			marketRepository.delete(idMarket);
			// Flush to get potential exception
			marketRepository.flush();

		} catch (ObjectRetrievalFailureException e) {
			String message = "Error deleting market " + idMarket;
			LOG.error(message, e);
			throw new InvalidMarketException(message, e);
		} catch (DataIntegrityViolationException e) {
			// should not occur here but could in more complex application
			String message = "cannot delete market " + idMarket;
			LOG.error(message, e);
			throw new InvalidMarketException(message, e);
		} catch (DataAccessException e) {
			String message = "Error deleting market " + idMarket;
			LOG.error(message, e);
			throw new TechnicalException(message, e);
		}

	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public MarketBean getMarket(Integer idMarket) throws NotFoundException {

		MarketBean marketBean = null;

		try {
			Market marketPersistant = marketRepository.findOne(idMarket);
			if (marketPersistant == null) {
				String message = "Market #" + idMarket + " not available";
				LOG.error(message);
				throw new NotFoundException(message);
			}
			marketBean = MarketTransform.persistant2Bean(marketPersistant);
		} catch (ObjectRetrievalFailureException e) {
			String message = "Invalid market";
			LOG.error(message, e);
			throw new TechnicalException(message, e);
		} catch (DataAccessException e) {
			String message = "Data not available";
			LOG.error(message, e);
			throw new TechnicalException(message, e);
		}

		marketBean = gererMarche.consultMarket(idMarket);

		return marketBean;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public List<MarketBean> getMarketByName(String name) throws NotFoundException {

		List<MarketBean> listMarkets = new ArrayList<MarketBean>();

		// *************/
		// First : get markets from database
		// *************/

		List<Market> marketsPersistants = null;

		try {
			if (name != null && !name.equals("")) {

				marketsPersistants = marketRepository.findByNameContaining(name);

			} else {

				marketsPersistants = marketRepository.findAll();

			}
		} catch (DataAccessException e) {
			String message = "Probleme d'acces aux donnees";
			LOG.error(message, e);
			throw new TechnicalException(message, e);
		}

		// transform to DTO
		if (marketsPersistants != null && marketsPersistants.size() > 0) {
			listMarkets = MarketTransform.persistant2BeanCollection(marketsPersistants);
		}

		// *************/
		// SECOND : get markets from webservice
		// *************/

		// We always call findAllMarkets() webservice then the relevant markets
		// are selected

		for (MarketBean marketBean : gererMarche.findAllMarkets().values()) {
			if (name != null) {
				if (marketBean.getName().contains(name)) {
					listMarkets.add(marketBean);
				}
			} else {
				listMarkets.add(marketBean);
			}
		}

		// scan result
		if (listMarkets == null || listMarkets.size() == 0) {
			String message = "no market found";
			LOG.info(message);
			throw new NotFoundException(message);
		}

		return listMarkets;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public long getMarketCountByName(String name) throws NotFoundException {

		List<MarketBean> listMarkets = new ArrayList<MarketBean>();

		// *************/
		// First : count markets from database
		// *************/

		long marketsPersistants = 0;

		try {
			if (name != null && !name.equals("")) {

				marketsPersistants = marketRepository.countMarketWithNameContaining(name);

			} else {

				marketsPersistants = marketRepository.count();

			}
		} catch (DataAccessException e) {
			String message = "Probleme d'acces aux donnees";
			LOG.error(message, e);
			throw new TechnicalException(message, e);
		}

		// *************/
		// SECOND : count markets from webservice
		// *************/

		// We always call findAllMarkets() webservice then the relevant markets
		// are selected

		for (MarketBean marketBean : gererMarche.findAllMarkets().values()) {
			if (name != null) {
				if (marketBean.getName().contains(name)) {
					listMarkets.add(marketBean);
				}
			} else {
				listMarkets.add(marketBean);
			}
		}

		return listMarkets.size() + marketsPersistants;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Page<MarketBean> getMarketByName(Pageable pageInfo, String name) throws NotFoundException {

		// *************/
		// First : get markets from database
		// *************/

		Page<Market> marketsPersistants = null;

		try {
			if (name != null && !name.equals("")) {

				marketsPersistants = marketRepository.findByNameContaining(pageInfo, name);

			} else {

				marketsPersistants = marketRepository.findAll(pageInfo);

			}
		} catch (DataAccessException e) {
			String message = "Probleme d'acces aux donnees";
			LOG.error(message, e);
			throw new TechnicalException(message, e);
		}

		// transform to DTO
		Page<MarketBean> pageMarketsBase = MarketTransform.persistant2BeanPage(marketsPersistants);

		List<MarketBean> listMarkets = new ArrayList<MarketBean>();
		listMarkets.addAll(pageMarketsBase.getContent());

		// *************/
		// SECOND : get markets from webservice
		// *************/

		// We always call findAllMarkets() webservice then the relevant markets
		// are selected

		for (MarketBean marketBean : gererMarche.findAllMarkets().values()) {
			if (name != null) {
				if (marketBean.getName().contains(name)) {
					listMarkets.add(marketBean);
				}
			} else {
				listMarkets.add(marketBean);
			}
		}

		// scan result
		if (listMarkets == null || listMarkets.size() == 0) {
			String message = "no market found";
			LOG.info(message);
			throw new NotFoundException(message);
		}

		Page<MarketBean> pageMarkets = new PageImpl<MarketBean>(listMarkets, pageInfo, listMarkets.size());

		return pageMarkets;
	}

	@Override
	public Page<MarketBean> findMarketByCriteria(Pageable pageInfo, MultiValuedMap<String, String> criteria)
			throws NotFoundException, InvalidQueryException {
		Page<Market> marketsPersistants = null;
		try {
			marketsPersistants = marketRepository.findByCriteria(pageInfo, criteria);
		} catch (InvalidDataAccessApiUsageException e) {
			String message = "Problem with your query : " + e.getMessage();
			LOG.error(message, e);
			throw new InvalidQueryException(message, e);
		} catch (DataAccessException e) {
			String message = "Data access problem";
			LOG.error(message, e);
			throw new TechnicalException(message, e);
		}

		// scan result
		if (marketsPersistants == null || marketsPersistants.getTotalElements() == 0) {
			String message = "no market found";
			LOG.info(message);
			throw new NotFoundException(message);
		}

		// transform to DTO
		Page<MarketBean> pageMarkets = MarketTransform.persistant2BeanPage(marketsPersistants);

		return pageMarkets;
	}

}